//
//  RateQueryVC.swift
//  ImGuider X
//
//  Created by 陆涛 on 2018/10/12.
//  Copyright © 2018 imguider. All rights reserved.
//

import UIKit

class RateQueryVC: BaseVC {

    @IBOutlet weak var tableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        setupData()
    }
    
    private func setupUI() {
        
        tableView.backgroundColor = kThemeBgColor
        
        tableView.register(UINib(nibName: "RateQueryCell", bundle: nil), forCellReuseIdentifier: "RateQueryCell")
        
        tableView.rowHeight = 96
    }
    
    private func setupData() {
        
        self.title = LocalizedString("rate_search")
        
        RateManager.share.reloadData()
        RateManager.share.toastText = {
            
            [weak self] errmsg in
            guard let `self` = self else { return }
            
            self.view.makeToast(errmsg)
        }
        
        RateManager.share.loadFinished = {
            
            [weak self] in
            guard let `self` = self else { return }
            
            self.tableView.reloadData()
        }
    }
}

extension RateQueryVC: UITableViewDataSource, UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return RateManager.share.storeRateList?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "RateQueryCell") as! RateQueryCell
        
        let rate = RateManager.share.storeRateList?[indexPath.row]
        
        cell.rate = rate
        
        cell.changeRateAction = {
            
            [weak self] rate in
            guard let `self` = self else { return }
            
            self.changeRateAction(rate: rate)
        }
        
        return cell
    }
    
    private func changeRateAction(rate:Rate?) {
        
        let vc = RateListVC()
        vc.selectRate = rate
        
        vc.selectFinished = {
            
            [weak self] in
            guard let `self` = self else { return }
            
            self.tableView.reloadData()
        }
        
        self.navigationController?.pushViewController(vc, animated: true)
    }
}
